#include "core/Server.h"
#include <iostream>
#include <thread>
#include <chrono>

Server::Server(/* args */)
{

}

Server::~Server()
{
}

void Server::init()
{
    m_stop = false;
    m_State = luaL_newstate();
    lua_State* L = m_State;
    luaL_openlibs(L);
    int loadret = luaL_loadfile(L, "./Resources/luasrc/main_game.lua");
    std::cout << "load file " << loadret << std::endl;
    loadret = lua_pcall(L, 0, 0, 0);
    int a = 5; 
}

void Server::run()
{
    while (!m_stop)
    {
        /* code */
        std::cout << "run once 5 sec" << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(5));
        std::cout << "input 1 to exit,0 continue run" << std::endl;

        testlua();

        read_input();

        handle_msg();
    }
    
}

void Server::testlua()
{
    int a =1;
    int b =2;
    lua_State* L = m_State;
    int curtop = lua_gettop(L);
    int ret = lua_getglobal(L, "MyTestAdd");
    curtop = lua_gettop(L);
    lua_pushnumber(L, ++a);
    lua_pushnumber(L, ++b);
    lua_pcall(L, 2, 1, 0);
    curtop = lua_gettop(L);
    std::cout << a << "+" << b << "=" << lua_tointeger(L, -1);
    lua_pop(L, 1);
}

void Server::exit()
{
    // clean up
    lua_close(m_State);
}

void Server::read_input()
{
    int a;
    std::cin >> a;
    if (a > 0)
    {
        m_stop = true;
    }
}

void Server::handle_msg()
{

}